<template>
  <a-spin :spinning="loading">
    <div v-if="info.isEdit && info.operationType !== 'Report'">
      <a-row style="width: 100%">
        <a-col :span="5" class="mb10 mt10">
          <span>上报人：</span>
          <span>{{ formInfo.reporterName }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>联系电话：</span>
          <span>{{ formInfo.reporterPhone }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>上报时间：</span>
          <span>{{ formInfo.reportTime }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>问题来源：</span>
          <span>{{ formInfo.issueSource }}</span>
        </a-col>
        <a-col :span="4" class="mb10 mt10">
          <span>是否公开信息：</span>
          <span>{{ formInfo.isPublic ? "是" : "否" }}</span>
        </a-col>
      </a-row>
      <a-row style="width: 100%">
        <a-col :span="5" class="mb10 mt10">
          <span>街道：</span>
          <span>{{ formInfo.road }} </span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>巷段：</span>
          <span>{{ formInfo.community }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>门牌号：</span>
          <span>{{ formInfo.houseNumber }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>不详：</span>
          <span>{{ formInfo.noDetail ? "是" : "否" }}</span>
        </a-col>
        <a-col :span="4" class="mb10 mt10">
          <span>是否接受回访：</span>
          <span>{{ formInfo.isFeedback ? "是" : "否" }}</span>
        </a-col>
      </a-row>
      <a-row style="width: 100%">
        <a-col :span="5" class="mb10 mt10">
          <span>问题类型：</span>
          <span>{{ formInfo.issueType }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>问题对象类型：</span>
          <span>
            {{ getRelatedObjectDisplay() }}
          </span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>关联对象：</span>
          <span> {{ formInfo && formInfo.relatedObjectName }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>问题等级：</span>
          <!-- :class="formInfo.issueLevel == " -->
          <span  :class="{
                  'urgency-level': true,
                  'level-0': formInfo.issueLevel == 1,
                  'level-1': formInfo.issueLevel == 2,
                  'level-2': formInfo.issueLevel == 3,
                }"
          >{{ (issueLevelList.find( (item) => item.value === formInfo.issueLevel ) || {}).label  }}</span>
        </a-col>
      </a-row>
      <a-spin :spinning="isDataLoading">
        <div
          class="grid-cards-container"
          v-if="
            formInfo.responsibleNetworkUserName &&
            formInfo.responsibleNetworkUserName.length > 0
          "
        >
          <div
            v-for="(item, index) in formInfo.responsibleNetworkUserName.split(
              ','
            )"
            :key="index"
            class="grid-card"
            :bordered="false"
          >
            <div class="card-header">
              <a-avatar icon="user" style="background-color: #0052d9" />
              <span class="title-card">所属网格</span>
              <a-icon
                :type="
                  selectedGrids.includes(index)
                    ? 'check-circle'
                    : 'check-circle-o'
                "
                class="select-icon"
              />
            </div>

            <div class="card-content">
              <div class="info-item">
                <span class="label">网格负责人：</span>
                <span class="value">{{ item }}</span>
              </div>
              <div class="info-item">
                <span class="label">责任部门：</span>
                <span class="value">{{
                  (formInfo.deptName && formInfo.deptName.split(",")[index]) ||
                  ""
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">责任网格：</span>
                <span class="value">{{
                  formInfo.heritageZoneName &&
                  formInfo.heritageZoneName.split(",")[index]
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </a-spin>
      <a-row style="width: 100%">
        <a-col :span="5" class="mb10 mt10">
          <span>紧急程度：</span>
          <span 
            :class="{
                  'urgency-level': true,
                  'level-0': formInfo.urgencyLevel == 0,
                  'level-1': formInfo.urgencyLevel == 1,
                  'level-2': formInfo.urgencyLevel == 2,
                }">{{
            (
              urgencyLevelList.find(
                (item) => item.value === formInfo.urgencyLevel
              ) || {}
            ).label
          }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>限时处理：</span>
          <span>{{ formInfo.deadlineTime }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>任务类型：</span>
          <span>{{ formInfo.relatedActionTypeName }}</span>
        </a-col>
        <a-col :span="5" class="mb10 mt10">
          <span>关联任务：</span>
          <span>{{
            (
              relatedTasksList.find(
                (item) => item.value === formInfo.relatedTasksId
              ) || {}
            ).label || ""
          }}</span>
        </a-col>
        <a-col :span="4" class="mb10 mt10">
          <span>是否督查督办：</span>
          <span 
               :class="{
                  'urgency-level': true,
                  'level-0': formInfo.urgencyLevel == '' || formInfo.urgencyLevel == null ,
                  'level-2': formInfo.dubanStatus == 1,
                }">{{
            formInfo && formInfo.dubanStatus == "0"
              ? "未督办"
              : formInfo.dubanStatus == "1"
              ? "已督办"
              : ""
          }}</span>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="luyin-style">
          <span style="width:100px;">来电录音：</span>
          <div class="tags-call" v-if="call_data.length > 0">
            <span  v-for="(item,index) in call_data" style="display:flex;align-items: center;">
              <span style="margin: 0 10px;">{{item.phone}}</span>
              <audio controls class="audio-style" key="index" style="height: 25px;width: 270px;">
                <source :src="item.url" type="audio/ogg" v-decorator="['mp3Link', { rules: [{ required: false }] }]" />
              </audio>
            </span>
          </div>
          
        </a-col>
        <a-col :span="24" class="luyin-style">
          <span style="width:100px;">附加录音：</span>
          <div class="tags-call" v-if="other_data.length > 0">
            <span  v-for="(item,index) in other_data" style="display:flex;align-items: center;">
              <span style="margin: 0 10px;">{{item.phone}}</span>
              <audio controls class="audio-style" key="index" style="height: 25px;width: 270px;">
                <source :src="item.url" type="audio/ogg" v-decorator="['otherMp3Link', { rules: [{ required: false }] }]" />
              </audio>
            </span>
          </div>
        </a-col>
        <a-col :span="24" class="mb10">
          <span>问题描述：</span>
          <span>{{ formInfo.issueDescription }}</span>
        </a-col>
        <a-col :span="24" class="mb10">
          <a-form-item
            label="附件（事件图片、视频、文件）"
            class="full-width-upload"
          >
            <!-- 查看详情模式下只显示文件预览 -->
            <div
              v-if="info.operationType === 'Detail' && info.isEdit"
              class="attachment-preview"
            >
              <div
                v-if="fileList && fileList.length > 0"
                class="file-preview-container"
              >
                <div
                  v-for="(file, index) in fileList"
                  :key="index"
                  class="file-preview-item"
                >
                  <!-- 图片文件显示预览 -->
                  <a-card
                    :bodyStyle="{ padding: '8px' }"
                    style="width: 150px; margin-bottom: 10px"
                    hoverable
                  >
                    <img
                      v-if="file.url && isImageFile(file.url)"
                      :src="file.url"
                      :alt="file.name"
                      class="preview-image"
                      @click="() => previewFile(file.url)"
                    />
                    <div
                      v-else
                      class="document-preview"
                      @click="() => previewFile(file.url)"
                    >
                      <a-icon
                        :type="getFileIcon(file.name || file.url)"
                        style="font-size: 32px"
                      />
                      <p class="file-name">
                        {{ getFileName(file.name || file.url) }}
                      </p>
                    </div>
                  </a-card>
                </div>
              </div>
              <div v-else class="no-attachments">
                <a-empty description="暂无附件" />
              </div>
            </div>

            <!-- 非查看详情模式下显示上传组件 -->
            <a-upload-dragger
              v-else
              :disabled="info.isEdit && info.operationType !== 'Report'"
              name="multipartFile"
              :multiple="true"
              :beforeUpload="beforeUpload"
              :fileList="fileList"
              accept=".png,.jpg,.jpeg,.txt,.doc,.docx,.csv,.xls,.xlsx,.pdf"
              listType="picture"
              action="http://114.132.184.120:6001/government-platform-center/common/uploadFile"
              class="horizontal-upload-list"
              @change="handleChangeFile"
              @remove="handleRemoveFile"
              v-decorator="['multipartFile', { rules: [{ required: false }] }]"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">点击上传拖拽文件到这里</p>
              <p class="ant-upload-hint">
                支持的文件类型：png、jpg、txt、doc、docx、csv、xls、xlsx、pdf
              </p>
              <!-- <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal> -->
            </a-upload-dragger>
          </a-form-item>
        </a-col>
      </a-row>
    </div>
    <a-form
      v-else
      ref="wdsbDetail"
      class="search-form"
      :form="searchForm"
      layout="inline"
      :label-col="labelCol"
    >
      <div class="mb10 overflow-x">
        <a-form-item label="上报人">
          <a-input
            style="width: 160px; margin-left: 10px"
            placeholder="请输入"
            v-decorator="[
              'reporterName',
              {
                rules: [{ required: true, message: '请输入上报人' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input
            style="width: 160px; margin-left: 10px"
            placeholder="请输入"
            v-decorator="[
              'reporterPhone',
              { rules: [{ required: true, message: '请输入联系电话' }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="上报时间">
          <a-date-picker
            style="width: 180px; min-width: 180px"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择上报时间"
            v-decorator="[
              'reportTime',
              { rules: [{ required: true, message: '请选择上报时间' }] },
            ]"
          />
        </a-form-item>

        <a-form-item label="是否公开信息">
          <a-checkbox
            v-decorator="[
              'isPublic',
              {
                valuePropName: 'checked',
                initialValue: false,
                rules: [{ required: false }],
              },
            ]"
          >
          </a-checkbox>
        </a-form-item>
        <a-form-item label="是否接受回访">
          <a-checkbox
            v-decorator="[
              'isFeedback',
              {
                valuePropName: 'checked',
                initialValue: false,
                rules: [{ required: false }],
              },
            ]"
          >
          </a-checkbox>
        </a-form-item>
      </div>
      <div class="mb10 overflow-x">
        <a-form-item label="街道">
          <a-select
            style="width: 160px; margin-left: 10px"
            :disabled="info.isEdit && info.operationType !== 'Report'"
            placeholder="请选择街道"
            allowClear
            show-search
            @change="handleChangeRoad"
            v-decorator="['road', { rules: [{ required: false }] }]"
          >
            <a-select-option v-for="d in roadList" :key="d.baseStreet">
              {{ d.baseStreet }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="巷段">
          <a-select
            style="width: 160px; margin-left: 10px"
            :disabled="info.isEdit && info.operationType !== 'Report'"
            placeholder="请选择巷段"
            allowClear
            show-search
            v-decorator="['community', { rules: [{ required: false }] }]"
            @change="handleChangeCommunity"
          >
            <a-select-option v-for="d in communityList" :key="d.baseLine">
              {{ d.baseLine }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="门牌号">
          <a-select
            style="width: 160px; margin-left: 10px"
            :disabled="info.isEdit && info.operationType !== 'Report'"
            placeholder="请选择门牌号"
            allowClear
            show-search
            v-decorator="['houseNumber', { rules: [{ required: false }] }]"
          >
            <a-select-option v-for="d in houseNumberList" :key="d.baseDetail">
              {{ d.baseDetail }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="不详">
          <a-checkbox
            :disabled="info.isEdit && info.operationType !== 'Report'"
            @change="handleChangeNoDetail"
            v-decorator="[
              'noDetail',
              {
                rules: [{ required: false }],
              },
            ]"
          >
          </a-checkbox>
        </a-form-item>
      </div>
      <div class="mb10 overflow-x">
        <a-form-item label="问题来源">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            v-decorator="[
              'issueSource',
              { rules: [{ required: false, message: '请选择问题来源' }] },
            ]"
          >
            <a-select-option
              v-for="d in issueSourceList"
              :key="d.value"
              :value="d.label"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="问题类型">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            v-decorator="[
              'issueType',
              { rules: [{ required: false, message: '请选择问题类型' }] },
            ]"
            @change="handleIssueTypeChange"
          >
            <a-select-option
              v-for="d in issueTypeList"
              :key="d.value"
              :value="d.label"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="问题对象类型">
          <a-cascader
            style="width: 160px; margin-left: 10px"
            :options="objectOptions"
            placeholder="请选择"
            @change="onChangeObject"
            v-decorator="[
              'relatedObjectData',
              { rules: [{ required: false }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="关联对象">
          <a-select
            show-search
            allowClear
            placeholder="请输入"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="
              searchNoData ? '无匹配数据' : searchLoading ? '搜索中...' : null
            "
            :loading="searchLoading"
            @search="handleSearch"
            @change="handleRelatedObjectChange"
            v-decorator="['relatedObjectName']"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :option-label-prop="'label'"
            :virtual="true"
            :list-height="256"
            style="width: 160px; margin-left: 10px"
          >
            <a-select-option
              v-for="d in relatedObjectMiniList"
              :key="d.value"
              :value="d.value"
              :label="d.label"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="问题等级">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            v-decorator="[
              'issueLevel',
              { rules: [{ required: false, message: '请选择问题等级' }] },
            ]"
          >
            <a-select-option v-for="d in issueLevelList" :key="d.value">
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </div>
      <a-spin :spinning="isDataLoading">
        <div class="grid-cards-container" v-if="mapData.length > 0">
          <div
            v-for="(item, index) in mapData"
            :key="index"
            class="grid-card"
            :class="{ 'grid-card-selected': selectedGrids.includes(index) }"
            :bordered="false"
            @click="toggleSelectGrid(index, item)"
          >
            <div class="card-header">
              <a-avatar icon="user" style="background-color: #0052d9" />
              <span class="title-card">所属网格</span>
              <a-icon
                :type="
                  selectedGrids.includes(index)
                    ? 'check-circle'
                    : 'check-circle-o'
                "
                class="select-icon"
              />
            </div>

            <div class="card-content">
              <div class="info-item">
                <span class="label">网格负责人：</span>
                <span class="value">{{ item.managerName }}</span>
              </div>
              <div class="info-item">
                <span class="label">责任部门：</span>
                <span class="value">{{ item.deptName || "" }}</span>
              </div>
              <div class="info-item">
                <span class="label">责任网格：</span>
                <span class="value">{{ item.heritageZone }}</span>
              </div>
            </div>
          </div>
        </div>
      </a-spin>
      <div class="mb10">
        <a-form-item label="紧急程度">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            v-decorator="[
              'urgencyLevel',
              { rules: [{ required: false, message: '请选择紧急程度' }] },
            ]"
          >
            <a-select-option v-for="d in urgencyLevelList" :key="d.value">
              {{ d.label }}
            </a-select-option>
            <!-- 其他状态选项 -->
          </a-select>
        </a-form-item>
        <a-form-item label="任务类型">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            @change="handleRelatedActionTypeChange"
            allowClear
            v-decorator="[
              'relatedActionTypeId',
              { rules: [{ required: false, message: '请选择任务类型' }] },
            ]"
          >
            <a-select-option
              v-for="d in relatedActionTypeList"
              :key="d.value"
              :value="d.value"
              :label="d.label"
            >
              {{ d.label }}
            </a-select-option>
            <!-- 其他状态选项 -->
          </a-select>
        </a-form-item>
        <a-form-item label="关联任务">
          <a-select
            style="width: 160px; margin-left: 10px"
            placeholder="请选择"
            allowClear
            v-decorator="[
              'relatedTasksId',
              { rules: [{ required: false, message: '请选择关联任务' }] },
            ]"
            @change="handleRelatedTasksChange"
          >
            <a-select-option
              v-for="d in relatedTasksList"
              :key="d.value"
              :value="d.value"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="限时处理">
          <a-date-picker
            show-time
            style="width: 180px; margin-left: 10px"
            :disabled="info.isEdit && info.operationType !== 'Report'"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            v-decorator="['deadlineTime', { rules: [{ required: false }] }]"
          />
        </a-form-item>
      </div>

      <a-row>
        <a-col :span="24" class="mb10 luyin-style">
          <a-form-item label="来电录音">
            <div class="tags-call" v-if="call_data.length > 0">
                <span  v-for="(item,index) in call_data" style="display:flex;align-items: center;">
                  <span style="margin: 0 10px;">{{item.phone}}</span>
                  <audio controls class="audio-style" key="index" style="height: 25px;width: 270px;">
                    <source :src="item.url" type="audio/ogg" v-decorator="['mp3Link', { rules: [{ required: false }] }]" />
                  </audio>
                  <img :src="deleteImg" alt="" style="height: 25px;width: 25px;margin-left: 10px;" @click="deleteCalltabs(index,'mp3Link')">
                </span>
            </div>
            
            <a-button type="dashed" @click="showmp3List = true , modelTitle='请选择来电录音文件',modelIndex='mp3Link'" style="margin-left:24px;">选择录音文件</a-button>
          </a-form-item>
        </a-col>
        <a-col :span="24" class="mb10">
          <a-form-item label="附加录音">
             <div class="tags-call" v-if="other_data.length > 0">
                <span  v-for="(item,index) in other_data" style="display:flex;align-items: center;">
                  <span style="margin: 0 10px;">{{item.phone}}</span>
                  <audio controls class="audio-style" key="index" style="height: 25px;width: 270px;">
                    <source :src="item.url" type="audio/ogg" v-decorator="['otherMp3Link', { rules: [{ required: false }] }]" />
                  </audio>
                  <img :src="deleteImg" alt="" style="height: 25px;width: 25px;margin-left: 10px;" @click="deleteCalltabs(index,'otherMp3Link')">
                </span>
            </div>
            <a-button type="dashed" @click="showmp3List = true , modelTitle='请选择附件录音文件',modelIndex='otherMp3Link'" style="margin-left:24px;">选择录音文件</a-button>

          </a-form-item>
        </a-col>
        <a-col :span="24" class="mb10">
          <a-form-item
            label="问题描述"
            style="width: 100%"
            class="full-width-textarea"
          >
            <span v-if="info.isEdit && info.operationType !== 'Report'">{{
              formInfo.issueDescription
            }}</span>
            <a-textarea
              v-else
              :disabled="info.isEdit && info.operationType !== 'Report'"
              placeholder="请输入"
              :rows="4"
              v-decorator="[
                'issueDescription',
                { rules: [{ required: true, message: '请输入问题描述' }] },
              ]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" class="mb10">
          <a-form-item
            label="附件（事件图片、视频、文件）"
            class="full-width-upload"
          >
            <!-- 查看详情模式下只显示文件预览 -->
            <div
              v-if="info.operationType === 'Detail' && info.isEdit"
              class="attachment-preview"
            >
              <div
                v-if="fileList && fileList.length > 0"
                class="file-preview-container"
              >
                <div
                  v-for="(file, index) in fileList"
                  :key="index"
                  class="file-preview-item"
                >
                  <!-- 图片文件显示预览 -->
                  <a-card
                    :bodyStyle="{ padding: '8px' }"
                    style="width: 150px; margin-bottom: 10px"
                    hoverable
                  >
                    <img
                      v-if="file.url && isImageFile(file.url)"
                      :src="file.url"
                      :alt="file.name"
                      class="preview-image"
                      @click="() => previewFile(file.url)"
                    />
                    <div
                      v-else
                      class="document-preview"
                      @click="() => previewFile(file.url)"
                    >
                      <a-icon
                        :type="getFileIcon(file.name || file.url)"
                        style="font-size: 32px"
                      />
                      <p class="file-name">
                        {{ getFileName(file.name || file.url) }}
                      </p>
                    </div>
                  </a-card>
                </div>
              </div>
              <div v-else class="no-attachments">
                <a-empty description="暂无附件" />
              </div>
            </div>

            <!-- 非查看详情模式下显示上传组件 -->
            <a-upload-dragger
              v-else
              :disabled="info.isEdit && info.operationType !== 'Report'"
              name="multipartFile"
              :multiple="true"
              :beforeUpload="beforeUpload"
              :fileList="fileList"
              accept=".png,.jpg,.jpeg,.txt,.doc,.docx,.csv,.xls,.xlsx,.pdf"
              listType="picture"
              :action="`http://114.132.184.120:8182/government-platform-center/common/uploadFile`"
              class="horizontal-upload-list"
              @change="handleChangeFile"
              @remove="handleRemoveFile"
              v-decorator="['multipartFile', { rules: [{ required: false }] }]"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">点击上传拖拽文件到这里</p>
              <p class="ant-upload-hint">
                支持的文件类型：png、jpg、txt、doc、docx、csv、xls、xlsx、pdf
              </p>
            </a-upload-dragger>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  
  
  
  
  <a-modal
      :title="modelTitle"
      :visible="showmp3List"
      width="70%"
      style="height:70%;"
      ok-text="确认"
      cancel-text="取消"
      @cancel="showmp3List = false"
      @ok="showmp3List=false,okCall()"
      :body-style="{ padding: '16px', maxHeight: '500px', overflowY: 'auto' }"
      :wrap-class-name="'fixed-height-modal'"
      centered
    >
     
    <a-table 
      :columns="columns_callList" 
      :data-source="callList" 
      :pagination="false" 
      :row-selection="{
        selectedRowKeys: modelIndex == 'mp3Link' ? selectedRowKeys : selectedRowKeys1,
        onChange:  onSelectChange,
      }">
       <span slot="call_type" slot-scope="text, record" class="item-style">
        <!-- caller_id_number 呼进号码
         呼出号码 -->
         <img :src="text == 'out' ? outImg : inImg " alt="" class="tellImg">
        {{ text == 'out' ? record.destination_number : record.caller_id_number }}

      </span>
      <div slot="record_url" slot-scope="text, record">
        <audio controls class="audio-style">
            <source :src="text" type="audio/ogg"/>
          </audio>
      </div>
    </a-table>
  </a-modal>
  </a-spin>

  
</template>

<script>
import dictMixin from "@/mixins/dictMixin";
import outImg from "@/assets/table/huchu.png";
import inImg from "@/assets/table/laidian.png";
import deleteImg from "@/assets/table/deleteImg.png";

import qs from "qs";
export default {
  name: "Sjsb",
  mixins: [dictMixin],
  props: {
    info: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      modelTitle:'',
      modelIndex:'',
      selectedRowKeys:[],
      selectedRowsCall:[],//选中来电的录音
      selectedRowKeys1:[],
      selectedRowsCall1:[],//选中附件的录音
      call_data:[],//选中后处理后的录音数据
      other_data:[],//选中后处理后的附件录音数据
      outImg:outImg,
      inImg:inImg,
      deleteImg:deleteImg,
      selectedGrids: [],
      labelCol: { style: { width: "80px", mariginLeft: "20px" } },
      previewVisible: false,
      objectOptions: [
        {
          value: "遗产",
          label: "遗产",
          children: [],
        },
        {
          value: "商家",
          label: "商家",
          children: [],
        },
        {
          value: "非商家",
          label: "非商家",
          children: [],
        },
      ],
      roadList: [],
      communityList: [], //巷段
      houseNumberList: [], //门牌号
      searchForm: this.$form.createForm(this, { name: "coordinated" }),
      relatedObjectList: [],
      relatedObjectMiniList: [],
      yichanList: [],
      merchantList: [],
      fileList: [],
      formInfo: {},
      relatedTasksList: [],
      loading: false,
      urlList: [],
      objectRequest: {
        api: "",
        paramKey: "",
        dataKey: "",
      },
      searchNoData: false,
      searchLoading: false,
      isDataLoading: false,
      //经纬度
      longitude: "",
      latitude: "",
      mapData: [],
      relatedTasksName: "",
      relatedObject: "",
      relatedObjectMini: "",
      relatedObjectName: "",
      relatedObjectId: "",
      relatedActionTypeName: "",
      callList:[],
      showmp3List:false,
      columns_callList:[
        {
          title: '通话时间',
          dataIndex: 'created_time',
          key: 'created_time',
        },
        {
          title: '通话记录',
          dataIndex: 'call_type',
          key: 'call_type',
          scopedSlots: { customRender: 'call_type' },
        },
        
        {
          title: '通话录音',
          dataIndex: 'record_url',
          key: 'record_url',
          width: 200,
          scopedSlots: { customRender: 'record_url' },
        },
      ]
    };
  },
  methods: {
    
    onSelectChange(selectedRowKeys, selectedRows){
      console.log('选中的数组==selectedRowKeys',selectedRowKeys)
      console.log('选中的数组==selectedRows',selectedRows)
   
      if(this.modelIndex == 'mp3Link'){ // 来电录音
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRowsCall = selectedRows;
      }      
      if(this.modelIndex == 'otherMp3Link'){ // 附件录音
        this.selectedRowKeys1 = selectedRowKeys;
        this.selectedRowsCall1 = selectedRows;
      }      
      
    },
    okCall(){
      let this_data = []
      if(this.modelIndex == 'mp3Link'){ // 来电录音
        this.selectedRowsCall.map(v=>{
          this_data.push({
            phone: v.call_type == 'out' ? v.destination_number : v.caller_id_number,
            url: v.record_url,
          })
        });
        if(this.searchForm.mp3Link){
          this.call_data = [...this.call_data ,...this_data];

        }else{
          this.call_data = this_data;
        }
        if(this.call_data.length > 0){ 
          this.fnCall(this.call_data)
        };
        }
      if(this.modelIndex == 'otherMp3Link'){ // 附件录音
          this.selectedRowsCall1.map(v=>{
            this_data.push({
              phone: v.call_type == 'out' ? v.destination_number : v.caller_id_number,
              url: v.record_url,
            })
          });
          if(this.searchForm.otherMp3Link){
            this.other_data = [...this.other_data ,...this_data];

          }else{
            this.other_data = this_data;
          }
          if(this.other_data.length > 0){ 
            this.fnother(this.other_data)
          };
        }
    },
    fnCall(data){
      let ss = [];
      data.map(v=>{
          ss.push(v.phone + ',' + v.url)
      });
      this.searchForm.mp3Link = ss.join(";");
    },
    fnother(data){
      let ss = [];
      data.map(v=>{
          ss.push(v.phone + ',' + v.url)
      });
      this.searchForm.otherMp3Link = ss.join(";");
    },
    deleteCalltabs(e,key){
      // console.log('删除标签索引--',e)
      if(key == 'mp3Link'){
        let datas = this.call_data;
        datas.splice(e,1);
        this.call_data = datas;
        if(datas.length <= 0){ return };
        let ss = [];
        datas.map(v=>{
            ss.push(v.phone + ',' + v.url)
        });
        this.searchForm.mp3Link = ss.join(",");
        console.log('删除来电录音标签--',this.call_data)
      }
      if(key =='otherMp3Link'){
        let datas = this.other_data;
        datas.splice(e,1);
        this.other_data = datas;
        if(datas.length <= 0){ return };
        let ss = [];
        datas.map(v=>{
            ss.push(v.phone + ',' + v.url)
        });
        this.searchForm.otherMp3Link = ss.join(",");
        console.log('删除附件录音标签--',this.call_data)
      }
     
    },
    // 获取来电录音列表
    getMp3Call(){
      this.$axios
        .post("/government-platform-center/case/getMp3Call")
        .then((res) => {
          if (res.data.code === 0 && res.data.data.length > 0) {
            console.log('获取录音--',)
            this.callList = JSON.parse(res.data.data);

          }
        })
    },
    handlePreview(file) {
      console.log("点击图片==", file);
      // if (!file.url && !file.preview) {
      //   file.preview = await getBase64(file.originFileObj);
      // }
      // previewImage.value = file.url || file.preview;
      // previewVisible.value = true;
      // previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
    },
    handleRelatedTasksChange(val) {
      if (val) {
        let one = this.relatedTasksList.find((item) => item.value === val);
        this.relatedTasksName = one.label;
      } else {
        this.relatedTasksName = "";
      }
    },
    handleRelatedActionTypeChange(val) {
      this.relatedTasksList = [];
      this.searchForm.setFieldsValue({
        relatedTasksId: "",
      });
      let findOne = this.relatedActionTypeList.find(
        (item) => item.value === val
      );
      this.relatedActionTypeName = findOne && findOne.label;
      // 只在有值且不是编辑模式时请求数据
      this.$axios
        .get("/government-platform-center/monitoringTasks/getMyTask", {
          params: {
            isSpa: val,
          },
        })
        .then((res) => {
          if (res.data.code === 0 && res.data.data) {
            // 格式化任务列表数据
            this.relatedTasksList = (res.data.data || []).map((item) => ({
              ...item,
              value: item.id,
              label: item.inspectionTaskName,
            }));
          } else {
            this.$message.error(res.data.msg || "获取关联任务失败");
            this.relatedTasksList = [];
          }
        })
        .catch((err) => {
          console.error("获取关联任务出错:", err);
          this.$message.error("获取关联任务出错");
          this.relatedTasksList = [];
        });
    },
    handleChangeFile(info) {
      // 保存当前的文件列表状态
      this.fileList = [...info.fileList];

      // 如果上传成功，则保存文件URL到urlList中
      if (
        info.file.status === "done" &&
        info.file.response &&
        info.file.response.data
      ) {
        this.urlList.push(info.file.response.data);

        // 为已上传文件添加URL属性以便预览
        this.fileList = this.fileList.map((file) => {
          if (file.response && file.response.data) {
            // 复制文件对象并添加URL属性
            file.url = file.response.data;
          }
          return file;
        });
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败`);
      }
    },
    handleRemoveFile(file) {
      // 从文件列表中移除
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;

      // 同时从urlList中移除对应的URL
      if (file.response && file.response.data) {
        const urlIndex = this.urlList.indexOf(file.response.data);
        if (urlIndex > -1) {
          this.urlList.splice(urlIndex, 1);
        }
      } else if (file.url) {
        const urlIndex = this.urlList.indexOf(file.url);
        if (urlIndex > -1) {
          this.urlList.splice(urlIndex, 1);
        }
      }

      return true; // 返回true允许移除操作
    },
    getFormData(val) {
      // 如果已经在加载数据，则跳过
      if (this.isDataLoading) {
        console.log("数据已经在加载中，跳过重复调用");
        return;
      }

      // 设置加载状态标志
      this.isDataLoading = true;

      // 将对象转换为 URLSearchParams 格式
      const params = new URLSearchParams();
      params.append("eventId", val.id);
      this.loading = true;
      this.$axios
        .post("/government-platform-center/case/getCaseDetail", params)
        .then((res) => {
          if (res.data.code === 0) {
            const { caseRecord, caseQuestion, casePaiqianList } = res.data.data;
            this.$emit("getPaiqianList", casePaiqianList);
            // 保存原始数据，稍后使用
            this.formInfo = {
              ...caseRecord,
              ...caseQuestion,
              isPublic: caseRecord.isPublic === 1,
              isFeedback: caseRecord.isFeedback === 1,
              // 确保路段信息正确映射
              road: caseRecord.road,
              community: caseRecord.community,
              baseLine: caseRecord.baseLine, // 兼容可能的字段名
              houseNumber: caseRecord.houseNumber,
              relatedActionTypeId:
                caseRecord.relatedActionTypeName === "日常任务" ? 0 : 1,
              deptName: "",
            };
            this.relatedTasksName = this.formInfo.relatedTasksName;
            this.relatedObject = this.formInfo.relatedObject;
            this.relatedObjectMini = this.formInfo.relatedObjectMini;
            this.relatedObjectName = this.formInfo.relatedObjectName;
            this.relatedActionTypeName = this.formInfo.relatedActionTypeName;

            // 获取网格
            if (this.formInfo.road) {
              this.handleChangeRoad(this.formInfo.road);
            }

            let heritageZoneIdArr =
              (this.formInfo.heritageZoneId &&
                this.formInfo.heritageZoneId.split(",")) ||
              [];
            // 获取部门名称
            if (heritageZoneIdArr.length > 0) {
              heritageZoneIdArr.forEach((item) => {
                this.$axios
                  .get("/government-platform-center/heritageZone/getDeptName", {
                    params: { id: item },
                  })
                  .then((res) => {
                    if (res.data.code === 0) {
                      let deptList = res.data.data;
                      this.formInfo.deptName += deptList.data + ",";
                    }
                  });
              });
            }
            // 如果存在relatedActionTypeId，则调用handleRelatedActionTypeChange
            if ([0, 1].includes(this.formInfo.relatedActionTypeId)) {
              this.handleRelatedActionTypeChange(
                this.formInfo.relatedActionTypeId
              );
            }
            // 调用接口
            if (this.formInfo.latitude && this.formInfo.longitude) {
              this.latitude = this.formInfo.latitude;
              this.longitude = this.formInfo.longitude;
              this.callApiWithValues();
            }

            // 处理已上传的文件链接
            if (caseQuestion.materialLink) {
              const links = caseQuestion.materialLink.split(",");
              this.urlList = links;

              // 将已有文件转换为fileList格式
              this.fileList = links.map((url, index) => {
                const fileName = url.substring(url.lastIndexOf("/") + 1);
                return {
                  uid: `-${index}`, // 负数表示已经存在的文件
                  name: fileName,
                  status: "done",
                  url: url, // 用于预览
                  thumbUrl: url.match(/\.(png|jpg|jpeg)$/i) ? url : null, // 为图片提供缩略图
                };
              });

              this.formInfo.materialLink = this.urlList.join(",");
            }

            // 使用延时函数确保表单已渲染
            setTimeout(async () => {
              try {
                // 初始化问题对象类型
                if (
                  this.formInfo.relatedObject &&
                  this.formInfo.relatedObject.length > 0
                ) {
                  await this.onChangeObject([
                    this.formInfo.relatedObject,
                    this.formInfo.relatedObjectMini,
                  ]);
                }

                // 再次延迟，等待关联对象数据加载
                setTimeout(() => {
                  try {
                    // 使用updateFields代替直接setFieldsValue
                    const fields = {};

                    // 通过遍历表单实例获取所有已注册的字段名
                    // 这样只会为已注册的字段设置值
                    const formFields = this.searchForm.getFieldsValue();

                    // 只有已存在于表单中的字段才设置值
                    Object.keys(formFields).forEach((key) => {
                      if (key === "relatedObject") {
                        fields[key] = {
                          value: this.formInfo.relatedObject,
                        };
                      } else if (key === "relatedObjectData") {
                        // 确保relatedObject和relatedObjectMini都存在且有值
                        if (
                          this.formInfo.relatedObject &&
                          this.formInfo.relatedObjectMini
                        ) {
                          fields[key] = {
                            value: [
                              this.formInfo.relatedObject,
                              this.formInfo.relatedObjectMini,
                            ],
                          };
                        }
                      } else if (key === "isPublic" || key === "isFeedback") {
                        // 对于复选框字段使用正确的属性设置
                        const value = !!this.formInfo[key]; // 确保是布尔值
                        fields[key] = {
                          value: value, // 由v-decorator处理为checked
                        };
                      } else if (this.formInfo[key] !== undefined) {
                        fields[key] = {
                          value: this.formInfo[key],
                        };
                      }
                    });
                    // 只使用setFields一次设置所有字段
                    this.searchForm.setFields(fields);
                    // 加载关联对象数据
                    if (this.formInfo.relatedObjectName) {
                      this.handleSearch();
                    }
                  } catch (err) {
                    console.error("设置表单字段值出错:", err);
                  }
                }, 100);
              } catch (error) {
                console.error("初始化表单数据出错:", error);
              }
            }, 200);
            // 获取录音列表
            if(this.formInfo.mp3Link){
              let datas = this.parsePhoneRecords(this.formInfo.mp3Link);
                console.log('案件详情的录音列表',datas);
                this.formInfo.mp3Link = '';
                this.searchForm.mp3Link = this.formInfo.mp3Link;
               
                this.call_data = datas;
                if(datas.length > 0){ 
                  this.fnCall(datas)
                };
            }
            // 获取附件录音列表
            if(this.formInfo.otherMp3Link){
              let datas = this.parsePhoneRecords(this.formInfo.otherMp3Link);
                console.log('案件详情的附件录音列表',datas);
                this.formInfo.otherMp3Link = '';
                this.searchForm.otherMp3Link = this.formInfo.otherMp3Link;
               
                this.other_data = datas;
                if(datas.length > 0){ 
                  this.fnother(datas)
                };
            }
          }
        })
        .finally(() => {
          this.loading = false;
          // 重置加载状态标志
          this.isDataLoading = false;
        });
    },
    parsePhoneRecords(str) {
      return str
        .split(';') // 按分号切割成独立记录
        .filter(item => item.trim()) // 过滤空字符串
        .map(item => {
          // 找到第一个逗号位置 (处理URL可能包含逗号的情况)
          const firstCommaIndex = item.indexOf(',');
          
          // 处理异常格式 (如果不存在逗号则跳过)
          if (firstCommaIndex === -1) return null;

          return {
            phone: item.slice(0, firstCommaIndex).trim(),
            url: item.slice(firstCommaIndex + 1).trim()
          };
        })
        .filter(Boolean); // 过滤无效条目
    },
    beforeUpload(file) {
      // 获取文件扩展名
      const fileName = file.name.toLowerCase();
      const fileExt = fileName.substring(fileName.lastIndexOf("."));

      // 允许的文件扩展名列表
      const allowedExtensions = [
        ".png",
        ".jpg",
        ".jpeg",
        ".txt",
        ".doc",
        ".docx",
        ".csv",
        ".xls",
        ".xlsx",
        ".pdf",
      ];

      const isValidType = allowedExtensions.includes(fileExt);
      if (!isValidType) {
        this.$message.error(
          "只支持 png、jpg、txt、doc、docx、csv、xls、xlsx、pdf 格式的文件！"
        );
        return false;
      }

      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("文件大小不能超过 10MB！");
        return false;
      }

      return true;
    },
    loadRoadData() {},
    handleSearch(value) {
      if (value) {
        if (!this.objectRequest || !this.objectRequest.api) {
          this.$message.error("请先选择问题对象类型");
          return;
        }

        // 设置加载状态
        this.searchLoading = true;
        this.searchNoData = false;

        let url = "";
        let params = null;

        // 特殊处理商家类型的请求
        if (this.objectRequest.paramKey === "merchantName") {
          url = this.objectRequest.api;
          // 商家类型使用JSON格式传参
          params = {
            current: 10000,
            offset: 1,
            merchantName: value,
          };
        } else {
          // 其他类型在URL上附加查询参数
          url = `${this.objectRequest.api}&${this.objectRequest.paramKey}=${value}`;
          params = {}; // 空对象或不传
        }

        // 发送请求
        this.$axios
          .post(url, params)
          .then((res) => {
            if (res.data.code === 0) {
              // 从嵌套对象中获取数据
              const getNestedValue = (obj, path) => {
                // 处理数组访问格式，如 "data[data]"
                if (path.includes("[") && path.includes("]")) {
                  const parts = path.split("[");
                  const firstKey = parts[0];
                  const secondKey = parts[1].replace("]", "");
                  return obj[firstKey][secondKey];
                }
                // 处理点访问格式，如 "data.data"
                else if (path.includes(".")) {
                  return path
                    .split(".")
                    .reduce(
                      (o, key) => (o && o[key] !== undefined ? o[key] : null),
                      obj
                    );
                }
                // 处理直接访问，如 "data"
                else {
                  return obj[path];
                }
              };

              // 获取数据
              let dataList = null;
              try {
                dataList = getNestedValue(res.data, this.objectRequest.dataKey);
              } catch (error) {
                console.error("获取数据失败：", error);
                this.$message.error("获取关联对象数据格式错误");
                this.searchNoData = true;
                return;
              }

              // 格式化为选择器需要的数据格式
              if (dataList && Array.isArray(dataList)) {
                // 限制最大显示100条结果
                // const limitedDataList = dataList.slice(0, 100);
                this.relatedObjectMiniList = dataList.map((item) => ({
                  ...item,
                  value: item[this.objectRequest.value],
                  label: item[this.objectRequest.label],
                }));
                // // 如果结果被截断，通知用户
                // if (dataList.length > 100) {
                //   this.$message.info(
                //     `共找到 ${dataList.length} 条记录，仅显示前 100 条`
                //   );
                // }

                // 设置无数据状态
                this.searchNoData = this.relatedObjectMiniList.length === 0;
              } else {
                this.relatedObjectMiniList = [];
                this.searchNoData = true;
              }
            } else {
              this.$message.error(res.data.msg || "获取关联对象失败");
              this.searchNoData = true;
            }
          })
          .catch((err) => {
            console.error("请求失败：", err);
            this.$message.error("获取关联对象失败");
            this.searchNoData = true;
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        // this.relatedObjectMiniList = [];
        // this.searchNoData = false;
      }
    },
    // 获取表单值
    getFormValues() {
      console.log('测试测试获取录音了',this.searchForm.mp3Link)
      return new Promise((resolve, reject) => {
        this.searchForm.validateFields((err, values) => {
          if (!err) {
            let responsibleNetworkUserId = "";
            let responsibleNetworkUserName = "";
            let heritageZoneId = "";
            let heritageZoneName = "";
            if (this.selectedGrids.length > 0) {
              let filterData = this.mapData.filter((item, index) =>
                this.selectedGrids.includes(index)
              );
              responsibleNetworkUserId = filterData
                .map((item) => item.managerId)
                .join(",");
              responsibleNetworkUserName = filterData
                .map((item) => item.managerName)
                .join(",");
              heritageZoneId = filterData.map((item) => item.id).join(",");
              heritageZoneName = filterData
                .map((item) => item.heritageZone)
                .join(",");
            }
            // 确保将布尔值转换为0/1
            const formattedValues = {
              ...(this.info.isEdit && this.info.operationType !== "Report"
                ? this.formInfo
                : values),
              isPublic: values.isPublic ? 1 : 0,
              isFeedback: values.isFeedback ? 1 : 0,
              materialLink: this.urlList.join(","),
              relatedTasksName: this.relatedTasksName,
              relatedObject: this.relatedObject,
              relatedObjectMini: this.relatedObjectMini,
              relatedObjectName: this.relatedObjectName,
              relatedObjectId: this.relatedObjectId,
              relatedActionTypeName: this.relatedActionTypeName,
              responsibleNetworkUserId: responsibleNetworkUserId,
              responsibleNetworkUserName: responsibleNetworkUserName,
              heritageZoneId: heritageZoneId,
              heritageZoneName: heritageZoneName,
              mp3Link: this.searchForm.mp3Link,
              otherMp3Link: this.searchForm.otherMp3Link
            };
            console.log(formattedValues, "formattedValues");
            resolve(formattedValues);
          }
        });
      });
    },
    handleChangeNoDetail(val) {
      this.searchForm.setFieldsValue({
        houseNumber: val.target.checked ? "不详" : "",
      });
    },
    // 事发路段
    getRoadData() {
      this.$axios
        .post("/government-platform-center/case/getAddressArea")
        .then((res) => {
          if (res.data.code === 0) {
            // 使用formatRoadData处理数据
            this.roadList = res.data.data;
          }
        });
    },
    // 获取巷段
    handleChangeRoad(val) {
      let areaData = this.roadList.find((item) => item.baseStreet === val);
      this.longitude = areaData && areaData.lng;
      this.latitude = areaData && areaData.lat;
      this.callApiWithValues();

      const params = new URLSearchParams();
      this.searchForm.setFieldsValue({
        community: undefined,
        houseNumber: undefined,
      });
      this.houseNumberList = [];
      params.append("area", val);
      this.$axios
        .post("/government-platform-center/case/getAddressStreet", params)
        .then((res) => {
          if (res.data.code === 0) {
            this.communityList = res.data.data;
          }
        });
    },
    // 获取门牌号
    async handleChangeCommunity(val) {
      let areaData = this.communityList.find((item) => item.baseLine === val);
      this.longitude = areaData && areaData.lng;
      this.latitude = areaData && areaData.lat;
      this.searchForm.setFieldsValue({
        houseNumber: undefined,
      });

      try {
        // 等待获取表单值
        // const formValues = await this.getFormValues(); // 这里讲道理不需要校验是否填了，直接获取绑定的值

        const params = new URLSearchParams();
        params.append("area", this.searchForm.getFieldValue("road"));
        params.append("street", val);

        const res = await this.$axios.post(
          "/government-platform-center/case/getAddressNumber",
          params
        );

        if (res.data.code === 0) {
          // 使用formatRoadData处理数据
          this.houseNumberList = res.data.data;
        } else {
          this.$message.error(res.data.msg || "获取门牌号失败");
        }
      } catch (error) {
        console.error("获取门牌号时出错:", error);
        this.$message.error("获取门牌号时出错");
      }
    },
    onChangeObject(val) {
      let [first, second] = val;
      this.relatedObject = first;
      this.relatedObjectMini = second;
      // 清除已选择的关联对象
      this.relatedObjectMiniList = [];
      this.searchNoData = false;
      this.searchLoading = false;

      // 只在非编辑模式下重置表单值
      if (!(this.info.isEdit && this.info.operationType !== "Report")) {
        this.searchForm.setFieldsValue({
          relatedObjectName: undefined,
        });
      }

      // 在编辑状态下，确保级联选择器显示正确的值
      if (this.info.isEdit) {
        this.searchForm.setFieldsValue({
          relatedObjectData: [first, second],
        });
      }

      if (first === "遗产") {
        this.objectRequest = {
          api: "/government-platform-center/xunjian/mini/index/searchHeritageList?current=10000&offset=1",
          paramKey: "search",
          dataKey: "data[data]",
          value: "id",
          label: "name",
        };
      } else if (first === "商家") {
        this.objectRequest = {
          api: "/government-platform-center/xunjian/merchantInfo/queryByPage",
          paramKey: "merchantName",
          dataKey: "data",
          value: "merchantId",
          label: "merchantName",
        };
      } else {
        this.objectRequest = {
          api: "/government-platform-center/xunjian/mini/index/getLivePersionList?current=10000&offset=1",
          paramKey: "name",
          dataKey: "data",
          value: "id",
          label: "name",
        };
      }

      // 如果是编辑模式并且有关联对象ID，加载关联对象数据
      if (
        this.info.isEdit &&
        this.info.operationType !== "Report" &&
        this.formInfo.relatedObjectName
      ) {
        this.loadRelatedObjectData();
      }

      // 检查三个字段是否都有值
      this.checkAndCallApi();

      return Promise.resolve(); // 确保返回Promise以支持async/await
    },
    // 添加加载关联对象数据的方法
    loadRelatedObjectData() {
      if (!this.objectRequest.api || !this.formInfo.relatedObjectName) return;

      this.searchLoading = true;

      let url = "";
      let params = null;

      // 特殊情况下使用ID查询，确保能加载正确数据
      if (this.objectRequest.paramKey === "merchantName") {
        url = this.objectRequest.api;
        params = {
          current: 10000,
          offset: 1,
          merchantId: this.formInfo.relatedObjectName,
        };
      } else {
        url = `${this.objectRequest.api}&id=${this.formInfo.relatedObjectName}`;
        params = {};
      }

      // 发送请求加载关联对象详情
      this.$axios
        .post(url, params)
        .then((res) => {
          if (res.data.code === 0) {
            const getNestedValue = (obj, path) => {
              // 和handleSearch方法中相同的逻辑...
              if (path.includes("[") && path.includes("]")) {
                const parts = path.split("[");
                const firstKey = parts[0];
                const secondKey = parts[1].replace("]", "");
                return obj[firstKey][secondKey];
              } else if (path.includes(".")) {
                return path
                  .split(".")
                  .reduce(
                    (o, key) => (o && o[key] !== undefined ? o[key] : null),
                    obj
                  );
              } else {
                return obj[path];
              }
            };

            let dataList = null;
            try {
              dataList = getNestedValue(res.data, this.objectRequest.dataKey);
            } catch (error) {
              console.error("获取关联对象数据失败：", error);
              return;
            }

            if (dataList && Array.isArray(dataList)) {
              this.relatedObjectMiniList = dataList.map((item) => ({
                ...item,
                value: item[this.objectRequest.value],
                label: item[this.objectRequest.label],
              }));
              console.log("加载的关联对象数据:", this.relatedObjectMiniList);
            }
          }
        })
        .catch((err) => {
          console.error("加载关联对象失败:", err);
        })
        .finally(() => {
          this.searchLoading = false;
        });
    },
    // 处理关联对象选择变化
    handleRelatedObjectChange(value) {
      if (value) {
        let findOne = this.relatedObjectMiniList.find(
          (item) => item.value === value
        );
        this.relatedObjectName = findOne.label;
        this.relatedObjectId = findOne.value;

        // 添加这行代码来更新表单显示
        this.searchForm.setFieldsValue({ relatedObjectId: value });

        this.checkAndCallApi();
      }
    },
    // 添加检查三个字段并调用接口的方法
    checkAndCallApi() {
      // 获取表单当前值
      const formValues = this.searchForm.getFieldsValue();
      const issueType = formValues.issueType;
      const relatedObject = formValues.relatedObject;
      const relatedObjectMini = formValues.relatedObjectName;

      // 检查三个字段是否都有值
      if (
        issueType &&
        relatedObject &&
        relatedObject.length > 0 &&
        relatedObjectMini
      ) {
        let areaData = this.relatedObjectMiniList.find(
          (item) => item.value === relatedObjectMini
        );
        this.longitude = areaData.lng;
        this.latitude = areaData.lat;
        this.callApiWithValues(issueType, relatedObject, relatedObjectMini);
      } else {
        console.log("字段值不完整，不调用接口", {
          issueType,
          relatedObject,
          relatedObjectMini,
        });
      }
    },
    // 调用接口的方法
    callApiWithValues(issueType, relatedObject, relatedObjectMini) {
      // 构建请求参数
      const data = {
        longitude: this.longitude,
        latitude: this.latitude,
      };

      // 发送请求到后端接口
      this.isDataLoading = true;
      this.$axios
        .post(
          "/government-platform-center/xunjian/patrolInspection/searchMap",
          data
        )
        .then((res) => {
          if (res.data.code === 0) {
            this.mapData = (res.data.data || []).map((ele) => {
              let itemOne = JSON.parse(ele.manager);
              let item = itemOne[2].split("/**/");
              return {
                ...ele,
                managerName: item[1],
                managerId: item[0],
                deptId: itemOne[1],
              };
            });
            let selectString = this.formInfo.heritageZoneId || "";
            let heritageZoneIdArr = selectString.split(",") || [];
            if (heritageZoneIdArr.length > 0) {
              heritageZoneIdArr.forEach((id) => {
                // 去除可能的空格
                id = id.trim();
                // 修改查找逻辑，处理类型不匹配的情况
                let selectIndex = res.data.data.findIndex(
                  (item) => String(item.id) === String(id)
                );

                if (selectIndex !== -1) {
                  this.selectedGrids.push(selectIndex);
                }
              });
            }
            console.log(this.selectedGrids, "this.selectedGrids");
            // 这里可以处理返回的数据
          } else {
            console.error("接口调用失败:", res.data.msg || "未知错误");
          }
        })
        .catch((err) => {
          console.error("接口请求异常:", err);
        })
        .finally(() => {
          this.isDataLoading = false;
        });
    },
    // 判断是否为图片文件
    isImageFile(url) {
      if (!url) return false;
      return /\.(png|jpg|jpeg|gif|bmp)$/i.test(url);
    },
    // 获取文件图标
    getFileIcon(fileName) {
      if (!fileName) return "file";

      const ext = fileName.split(".").pop().toLowerCase();
      const iconMap = {
        pdf: "file-pdf",
        doc: "file-word",
        docx: "file-word",
        xls: "file-excel",
        xlsx: "file-excel",
        ppt: "file-ppt",
        pptx: "file-ppt",
        txt: "file-text",
        jpg: "picture",
        jpeg: "picture",
        png: "picture",
        gif: "picture",
      };

      return iconMap[ext] || "file";
    },
    // 获取文件名
    getFileName(path) {
      if (!path) return "";
      return path.split("/").pop();
    },
    // 预览文件
    previewFile(url) {
      if (!url) {
        this.$message.warning("没有可预览的文件");
        return;
      }

      if (this.isImageFile(url)) {
        // 如果是图片类型，可以尝试使用预览组件(如果存在)
        if (this.$preview && typeof this.$preview.open === "function") {
          this.$preview.open({
            src: url,
            downloadable: true,
          });
        } else {
          // 否则直接在新窗口打开
          window.open(url, "_blank");
        }
      } else {
        // 非图片文件直接在新窗口打开
        window.open(url, "_blank");
      }
    },
    getRelatedObjectDisplay() {
      console.log(this.formInfo, "this.formInfo.relatedObject");
      if (!this.formInfo.relatedObject || !this.formInfo.relatedObject.length)
        return "暂无";

      let first = "";
      let second = "";

      // 查找第一级数据
      if (this.formInfo.relatedObject) {
        const firstOption = this.objectOptions.find(
          (item) => item.value === this.formInfo.relatedObject
        );
        first = firstOption
          ? firstOption.label
          : this.formInfo.relatedObject[0];
      }

      // 查找第二级数据
      if (this.formInfo.relatedObjectMini) {
        // 寻找所有二级菜单中匹配的项
        for (const option of this.objectOptions) {
          if (option.children && option.children.length) {
            const secondOption = option.children.find(
              (item) => item.label === this.formInfo.relatedObjectMini
            );
            if (secondOption) {
              second = secondOption.label;
              break;
            }
          }
        }

        // 如果没找到，直接显示值
        if (!second) {
          second = this.formInfo.relatedObjectMini;
        }
      }

      return this.formInfo.relatedObject && this.formInfo.relatedObjectMini
        ? `${this.formInfo.relatedObject}/${this.formInfo.relatedObjectMini}`
        : this.formInfo.relatedObject ||
            this.formInfo.relatedObjectMini ||
            "暂无";
    },
    // 处理问题类型变化
    handleIssueTypeChange(value) {
      console.log("选择的问题类型：", value);
      // 检查三个字段是否都有值
      this.checkAndCallApi();
    },
    toggleSelectGrid(index, item) {
      const selectedIndex = this.selectedGrids.indexOf(index);
      if (selectedIndex === -1) {
        // 如果未选中，则添加到选中数组中
        this.selectedGrids.push(index);
      } else {
        // 如果已选中，则从选中数组中移除
        this.selectedGrids.splice(selectedIndex, 1);
      }
      // 触发选中网格改变事件，方便父组件获取选中数据
    },
  },
  created() {
    // 在组件创建时设置初始loading状态为true
    this.loading = true;
    this.getMp3Call();
    this.getDictData({
      code: "QUESTION_SOURCE_CODE", // 问题来源
      name: "issueSourceList",
    });
    this.getDictData({
      code: "QUESTION_TYPE_CODE", // 问题类型
      name: "issueTypeList",
    });

    // 获取遗产类型数据
    this.getSpecialDictData({
      code: "yichan_code", // 遗产类型
      name: "yichanList",
      callback: (data) => {
        // 获取到遗产数据后，立即更新 objectOptions
        this.objectOptions[0].children = data;
        console.log(this.objectOptions, "this.objectOptions");
      },
    });

    // 获取商家类型数据
    this.getSpecialDictData({
      code: "merchant_code", // 商家类型
      name: "merchantList",
      callback: (data) => {
        // 获取到商家数据后，立即更新 objectOptions
        this.objectOptions[1].children = data;
      },
    });

    this.getRoadData();

    // 初始化数据完成后结束loading状态
    this.$nextTick(() => {
      // 如果info中有id，getFormData会自己处理loading状态
      if (!this.info.id) {
        this.loading = false;
      }
    });
  },
  watch: {
    info: {
      handler(val) {
        this.relatedTasksName = "";
        this.relatedObject = "";
        this.relatedObjectMini = "";
        this.relatedObjectName = "";
        this.relatedObjectId = "";
        this.relatedActionTypeName = "";
        if (val.id) {
          // 使用mounted钩子处理初始加载，只在watch触发时处理后续变化
          if (this._isMounted) {
            // 只在非初始化加载时调用getFormData
            setTimeout(() => {
              // 记录info变化时获取数据调用
              this.getFormData(val);
            }, 100);
          }
        } else {
          // 当info变化但没有id时，确保loading状态结束
          this.loading = false;
        }
      },
      deep: true,
      immediate: false, // 改为false，让mounted处理初始加载
    },
    // 监听 yichanList 变化
    yichanList: {
      handler(val) {
        if (val && val.length > 0) {
          this.objectOptions[0].children = val;
        }
      },
      immediate: true,
    },
    // 监听 merchantList 变化
    merchantList: {
      handler(val) {
        if (val && val.length > 0) {
          this.objectOptions[1].children = val;
        }
      },
      immediate: true,
    },
  },
  beforeMount() {
    // 标记组件即将挂载
    this._isMounted = false;
  },
  mounted() {
    // 标记组件已挂载
    this._isMounted = true;

    // 延迟获取数据确保表单渲染完成
    if (this.info.id) {
      setTimeout(() => {
        // 记录初始化时获取数据调用
        this.getFormData(this.info);
      }, 100);
    }
  },
};
</script>
<style lang="scss" scoped>
.overflow-x {
  overflow-x: auto;
}
.mb10 {
  margin-bottom: 10px;
}
.flex-row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  gap: 10px;
}
.flex-row-wrap {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 10px;
}
.flex-between {
  display: flex;
  justify-content: space-between;
  flex-wrap: nowrap;
}
.search-form {
  padding: 10px;
}
.search-form :deep(.ant-form-item) {
  display: flex;
  width: fit-content;
  margin-bottom: 16px;
}
.search-form :deep(.ant-form-item-label) {
  width: fit-content;
  text-align: right;
  padding-right: 8px;
}
.search-form :deep(.ant-form-item-control-wrapper) {
  flex: 1;
}
.grid-cards-container {
  display: flex;
  flex-wrap: wrap;
  /* justify-content: space-between; */
  align-items: center;
  gap: 16px;
  margin-top: 26px;
  margin-bottom: 26px;
}

.grid-card {
  width: calc(25%);
  height: 190px;
  background: #f7f9fc;
  border-radius: 8px;
  padding: 10px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.title-card {
  font-weight: 500;
  color: #333;
  margin-left: 10px;
  /* margin-bottom: 10px; */
}

.help-icon {
  margin-left: auto;
  color: #999;
}

.card-content {
  color: #666;
  padding-left: 40px;
}

.info-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #666;
}
.value {
  color: #333;
}
.flex-col {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 10px;
}
.full-width-textarea {
  width: 100% !important;
}
.full-width-textarea ::v-deep .ant-form-item-control-wrapper {
  width: calc(100% - 81px) !important;
}
.full-width-upload {
  width: 100% !important;
}
.full-width-upload ::v-deep .ant-form-item-control-wrapper {
  width: 100% !important;
}
.horizontal-upload-list {
  width: 100%;
}

/* 使用深度选择器修改上传列表样式 */
.horizontal-upload-list ::v-deep .ant-upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.horizontal-upload-list ::v-deep .ant-upload-list-item {
  width: 200px;
  margin-top: 8px !important;
  margin-bottom: 0 !important;
}

/* 文件名过长时显示省略号 */
.horizontal-upload-list ::v-deep .ant-upload-list-item-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 调整图片预览大小 */
.horizontal-upload-list
  ::v-deep
  .ant-upload-list-picture
  .ant-upload-list-item-thumbnail {
  width: 48px;
  height: 48px;
  object-fit: cover;
}

/* 调整操作按钮位置 */
.horizontal-upload-list ::v-deep .ant-upload-list-item-card-actions {
  right: 0;
}

/* 如果有些元素需要保持可点击（比如按钮），可以单独设置 */
.search-form .clickable {
  pointer-events: auto;
}

.attachment-preview {
  width: 100%;
}

.file-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.file-preview-item {
  cursor: pointer;
}

.preview-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
}

.document-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
}

.file-name {
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-attachments {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
.flex-row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  gap: 10px;
}
::v-deep .ant-select {
  width: 180px;
}
.grid-layout-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, minmax(80px, auto));
  gap: 10px;
  margin-bottom: 20px;
  width: 100%;
}

.grid-item {
  background-color: #f7f9fc;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.grid-item:hover {
  background-color: #e6f7ff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.luyin-style {
  margin: 20px 0;
  line-height: 40px;
  display: flex;
  align-items: center;
}
.audio-style {
  height: 40px;
}

/* 添加选中状态的样式 */
.grid-card-selected {
  background: #e6f7ff;
  border: 2px solid #0052d9;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
}

.select-icon {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 18px;
}

.grid-card-selected .select-icon {
  color: #0052d9;
}
.warning{
  color: rgb(230, 227, 75);

}
.danger{
  color: rgb(255, 77, 79);

}
.soso{
  color: rgb(24, 144, 255);
}
.urgency-level {
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;

  &.level-0 {
    background-color: #1890ff;
    color: #fff;
  }

  &.level-1 {
    background-color: #f7f588;
    color: #000;
  }

  &.level-2 {
    background-color: #ff4d4f;
    color: #fff;
  }
}
.item-style{
  display: flex;
  align-items: center;
}
.tellImg{
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.tags-call{
  display: flex;
  flex-wrap: wrap;
  // padding: 20px;
  margin-bottom: 10px;
}
/* 固定整体高度 */
.fixed-height-modal .ant-modal {
  top: 50% !important;
  transform: translateY(-50%) !important;
  height: 500px;
}

/* 内容滚动区域 */
.fixed-height-modal .ant-modal-body {
  height: calc(500px - 108px); /* 总高度 - 头部和底部高度 */
  overflow-y: auto;
}

/* 统一滚动条样式 */
.fixed-height-modal ::-webkit-scrollbar {
  width: 6px;
}
.fixed-height-modal ::-webkit-scrollbar-thumb {
  background: rgba(0,0,0,0.2);
  border-radius: 3px;
}
</style>
